import { Loading } from 'element-ui'
import Axios from 'axios'

// blob转文件并下载
const blob2file = (fileBlob, fileName) => {
  const blob = new Blob([fileBlob], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  })
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  downloadElement.style.display = 'none'
  downloadElement.href = href
  downloadElement.download = fileName || '下载' // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

/**
 * GET 下载文件
 * @param {url} url
 * @param {param} 参数
 */
const downFileGet = (url, param) => {
  let urlParam = ''
  Object.keys(param).map((key) => {
    urlParam += key + '=' + param[key] + '&'
  })
  // 此处生成的 url 末尾多一个 & , .substring 截取一下
  const href = `${location.origin}${url}?${urlParam}`
  console.log(url, href)
  const downloadElement = document.createElement('a')
  downloadElement.style.display = 'none'
  downloadElement.href = href
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement)
}

/**
 * 直接下载文件
 * @param {*} url
 * @param {*} filename
 */
export const downloadFile = (url, filename) => {
  const loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  link.download = filename
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  loading.close()
}

/**
 * 带参数下载文件
 * @param {*} url
 * @param {*} filename
 */
const downFilePost = async (downPath, data) => {
  const loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const res = await Axios({
      baseURL: process.env.VUE_APP_BASE_API,
      url: downPath,
      method: 'post',
      responseType: 'blob',
      data
    })
    // console.log('-=-=res', res)
    // 从content-disposition拿到后端返回的filename，并用decodeURI解码，防止乱码
    const fileName = decodeURI(res.headers['content-disposition'].split('=')[1])
    const blob = res.data
    const a = document.createElement('a')
    const url = window.URL.createObjectURL(blob)
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    loading.close()
  } catch (error) {
    loading.close()
  }
}

/**
 * 文件流下载
 * @param {*} url
 * @param {*} filename
 */
export const blobDownloadFile = (url, filename) => {
  const loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const a = document.createElement('a')
      const url = window.URL.createObjectURL(blob)
      a.href = url
      a.download = filename
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      loading.close()
    })
    .catch((error) => {
      console.error('下载文件时出错：', error)
      loading.close()
    })
}

export default {
  blob2file,
  downFileGet,
  downloadFile,
  blobDownloadFile,
  downFilePost
}
